// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');
const novel_tool = require('./util/novel_tool');
const fs = require('fs');

// This method is called when your extension is activated
// Your extension is activated the very first time the command is executed
let statusBar = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left)

var chapterBuf = ''
var chapterLine = []
var lineIndex = 0
var lineOffset = 0
var nextFlag = true
var TEXT_LENGTH = 54
var info = null;

/**
 * @param {vscode.ExtensionContext} context
 */
function activate(context) {

	// Use the console to output diagnostic information (console.log) and errors (console.error)
	// This line of code will only be executed once when your extension is activated
	console.log('Congratulations, your extension "moyu-plugin" is now active!');

	var that = this

	// The command has been defined in the package.json file
	// Now provide the implementation of the command with  registerCommand
	// The commandId parameter must match the command field in package.json
	


	let disposable = vscode.commands.registerCommand('moyu-plugin.helloWorld', function () {
		if(!statusBar) {
			statusBar  = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
		}

		statusBar.text = '你好，墨鱼艺术家';
  		statusBar.show();
	});

	

	let setNovelPath = vscode.commands.registerCommand('moyu-plugin.setNovelPath', function () {
		
		if(!statusBar) {
			statusBar  = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
		}

		vscode.window.showOpenDialog({ // 可选对象
			canSelectFiles:false, // 是否可选文件
			canSelectFolders:true, // 是否可选文件夹
			canSelectMany:false, // 是否可以选择多个
			defaultUri:vscode.Uri.file("/D:/"), // 默认打开本地路径
			openLabel:'确认'
		}).then(function(msg){
			let result = novel_tool.setNovelPath(vscode.Uri.parse(msg[0].toString()).path + '/novel')

			statusBar.text = result + 'was created'
			statusBar.show();
		})
	});


	let importNovel = vscode.commands.registerCommand('moyu-plugin.importNovel', function () {
		
		if(!statusBar) {
			statusBar  = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
		}
		
		vscode.window.showOpenDialog({ // 可选对象
			canSelectFiles:true, // 是否可选文件
			canSelectFolders:false, // 是否可选文件夹
			canSelectMany:false, // 是否可以选择多个
			defaultUri:vscode.Uri.file(""), // 默认打开本地路径
			openLabel:'确认'
		}).then(function(msg){
			that.novelPath = msg[0].path; 
			let storePath = vscode.workspace.getConfiguration().get('moyu-plugin.novelPath');
			novel_tool.parseNovel(that.novelPath, storePath);

			statusBar.text = that.novelPath;
			statusBar.show();
		})
	});

	let selectNovel = vscode.commands.registerCommand('moyu-plugin.selectNovel', function () {
		
		if(!statusBar) {
			statusBar  = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
		}

		let novelList = novel_tool.getNovelList()
		
		vscode.window.showQuickPick(novelList.list).then(selected => {
			let index = novelList.list.indexOf(selected)
			let novelpath = novelList.pathList[index];
			// 更新当前阅读小说地址
			vscode.workspace.getConfiguration().update('moyu-plugin.reading', novelpath, true);
			// 更新当前章节进度，data为info.json内容
			fs.readFile(novelpath + '/info.json',(err, data)=>{
				if(err) {
					console.log('open info.json error!\n' + err);
				}
				info = JSON.parse(data.toString());
				loadChapter(true)
			})
		});
		
		  
	});
	

	let nextLine = vscode.commands.registerCommand('moyu-plugin.nextLine', function () {
		if(!statusBar) {
			statusBar  = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
		}
		if (nextFlag == true) {
			lineIndex++;
		}
		
		// 显示
		if (lineIndex < chapterLine.length && lineIndex >= 0) {
			showLine()
		} else if (lineIndex < 0) {
			// 上一章
			prevChapter();
		} else if (lineIndex >= chapterLine.length) {
			// 下一章
			nextChapter();
		}
	});

	let preLine = vscode.commands.registerCommand('moyu-plugin.preLine', function () {
		if(!statusBar) {
			statusBar  = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
		}
		
		lineIndex--;
		
		// 显示
		if (lineIndex < chapterLine.length && lineIndex >= 0) {
			lineOffset = 0;
			showLine()
		} else if (lineIndex < 0) {
			// 上一章
			prevChapter();
		} else if (lineIndex >= chapterLine.length) {
			// 下一章
			nextChapter();
		}
	});

	context.subscriptions.push(disposable);
	context.subscriptions.push(nextLine);
	context.subscriptions.push(preLine);
	context.subscriptions.push(importNovel);
	context.subscriptions.push(setNovelPath);
	context.subscriptions.push(selectNovel);
}

// This method is called when your extension is deactivated
function deactivate() {}

function prevChapter() {
	// 更新进度
	info.process = info.process - 1;
	loadChapter(false)
}

function nextChapter() {
	// 更新进度
	info.process = info.process + 1;
	loadChapter(true)
}

function loadChapter(nextChatpterflag) {
	vscode.workspace.getConfiguration().update('moyu-plugin.process', info.process, true);
	// 加载当前章节内容缓存
	fs.readFile(info.Chapters[info.process - 1].path,(err, data)=>{ 
		if(err) {
			console.log(err);
		}
		chapterBuf = data.toString();
		chapterLine = chapterBuf.split('\n')
		chapterLine = chapterLine.filter((line) =>line.length > 0)
		lineIndex = nextChatpterflag ? 0 : chapterLine.length - 1;
		lineOffset = 0;
		nextFlag = true;

		

		// 显示
		if (lineIndex < chapterLine.length && lineIndex >= 0) {
			statusBar.text = chapterLine[lineIndex]
			statusBar.show()
		}
		
	})
}

function showLine() {
	statusBar.text = chapterLine[lineIndex].substring(lineOffset, lineOffset + TEXT_LENGTH)
	statusBar.show()
	if(lineOffset + TEXT_LENGTH >= chapterLine[lineIndex].length) {
		lineOffset = 0;
		nextFlag = true;
	} else {
		lineOffset = lineOffset + TEXT_LENGTH;
		nextFlag = false;
	}
}

module.exports = {
	activate,
	deactivate
}
